var db = require('../../config/db')
//查询
exports.search = (req,res)=>{
    if(req.query.tar == '1'){
      const userId = req.query.id;

    // 查询用户的土地资源
    db.query(`SELECT * FROM land_resource WHERE userid=?`, userId, (err, landResources) => {
        if (err) {
            console.error('查询土地资源出错：', err);
            return res.send({
                status: 500,
                message: '服务器错误',
            });
        }

        if (landResources.length < 1) {
            return res.send({
                status: 404,
                message: '无记录',
            });
        }

        let finalResults = [];
        let completedQueries = 0;

        // 遍历土地资源
        landResources.forEach(landResource => {
            // 查询土地块
            db.query(`SELECT * FROM land_parcel WHERE landresourceid=?`, landResource.id, (err, landParcels) => {
                if (err) {
                    console.error('查询土地块出错：', err);
                    return handleError(res);
                }

                if (landParcels.length < 1) {
                    return handleError(res, 404, '无记录');
                }

                // 遍历土地块
                landParcels.forEach(landParcel => {
                    // 查询菜地
                    db.query(`SELECT * FROM vegetable_plot WHERE landparcelid=?`, landParcel.id, (err, vegetablePlots) => {
                        if (err) {
                            console.error('查询菜地出错：', err);
                            return handleError(res);
                        }

                        if (vegetablePlots.length < 1) {
                            return handleError(res, 404, '无记录');
                        }

                        // 遍历菜地
                        vegetablePlots.forEach(vegetablePlot => {
                            // 查询种植成本
                            db.query(`SELECT * FROM planting_cost WHERE vegetableid=?`, vegetablePlot.id, (err, plantingCosts) => {
                                if (err) {
                                    console.error('查询种植成本出错：', err);
                                    return handleError(res);
                                }

                                // 处理查询结果
                                plantingCosts.forEach(plantingCost => {
                                    plantingCost.name = vegetablePlot.name;
                                    plantingCost.crops = vegetablePlot.crops;
                                    finalResults.push(plantingCost);
                                });

                                completedQueries++;

                                // 所有异步操作完成后，返回结果给前端
                                if (completedQueries === landResources.length) {
                                    return res.send({
                                        status: 200,
                                        message: '查询成功',
                                        data: finalResults,
                                    });
                                }
                            });
                        });
                    });
                });
            });
        });
    });
    function handleError(res, status = 500, message = '服务器错误') {
      return res.send({
          status: status,
          message: message,
      });
  }
    }else{
        ///管理员
        db.query(`select * from planting_cost`, (err, results) => {
            if (results.length > 0) {
                const promises = results.map((result) => {
                    return new Promise((resolve, reject) => {
                        db.query(`select * from vegetable_plot where id=?`, result.vegetableid, (err, results1) => {
                            if (err) {
                                reject(err);
                            } else {
                                result.name = results1[0].name;
                                result.crops = results1[0].crops;
                                resolve(result);
                            }
                        });
                    });
                });
        
                Promise.all(promises)
                    .then((updatedResults) => {
                        res.send({ // 返回前端信息
                            status: 200,
                            message: '查询成功',
                            data: updatedResults,
                        });
                    })
                    .catch((error) => {
                        res.send({ // 返回前端信息
                            status: 500,
                            message: '查询出错',
                            error: error,
                        });
                    });
            } else {
                res.send({ // 返回前端信息
                    status: 500,
                    message: '无数据',
                });
            }
        });
    }
}
//添加
exports.add =  (req , res)=>{
    if(req.body.tar == '1'){
    db.query(`select * from land_resource where userid=?`, [req.body.userid],(err, results) => {
        if (err) {
          return res.send({
            status: '500',
            message: '服务器错误',
          });
        }
        if(results.length <1){
            return res.send({
              status: '404',
              message: '添加失败：土地资源信息为空，请先添加',
            });
          }
        try {
          let finalResults = [];
          results.forEach((item, index) => {
            db.query(`select * from land_parcel where landresourceid=?`, results[index].id,(err, results1) =>{
                if(results1.length <1){
                    return res.send({
                      status: '404',
                      message: '添加失败：土地块信息为空，请先添加',
                    });
                  }
              results1.forEach((item1, index1) =>{
                //
                db.query(`select * from vegetable_plot where landparcelid=?`, results1[index1].id,(err, results2) =>{
                    if(results2.length <1){
                        return res.send({
                          status: '404',
                          message: '添加失败：菜地信息为空，请先添加',
                        });
                      }
                  finalResults.push(...results2);
                  if(index === results.length-1 && index1 === results1.length-1){
                    handleFinalResults(finalResults)
                  }
                })
              })
            })
          })
        } catch (error) {
          res.send({
            status: '500',
            message: '服务器错误：' + error.message,
          });
        }
      });
        // 处理最终结果
    function handleFinalResults(finalResults) {
    try {
      const targetPlot = finalResults.find(plot => plot.name == req.body.name);
      if (!targetPlot) {
        return res.send({
          status: '404',
          message: '添加失败，该菜地未拥有',
        });
      }else{
        db.query(`select * from planting_output where vegetableid=?`, targetPlot.id,(err, results3) =>{
          if (results3.length < 1) {
            return res.send({
              status: '404',
              message: '添加失败，该菜地的产能数据还没有',
            });
          }else{
            db.query(`select * from planting_cost where vegetableid=?`, targetPlot.id, (err, results5) => {
                //
                if(results5.length == 1){
                    res.send({ // 返回前端信息
                        status: 500,
                        message: '添加失败,该菜地已存在成本信息',
                    });
                }else{
                    const { id, name, tar, userid, ...rest } = req.body;
                    rest.vegetableid = targetPlot.id;
                    db.query('INSERT INTO planting_cost SET ?', rest,(err, results4) =>{
                    res.send({
                        status: 200,
                        message: '添加成功',
                    });
                    });
                }

            })
            
          }
        })
      }
    } catch (error) {
      res.send({
        status: '500',
        message: '服务器错误：' + error.message,
      });
    }
    }

    }else{
        db.query(`select * from vegetable_plot where name=?`, req.body.name, (err, results) => {
            if(results.length!= 1){
                res.send({ // 返回前端信息
                    status: 500,
                    message: '添加失败,不存在该菜地',
                });
            }else{
                db.query(`select * from planting_output where vegetableid=?`, results[0].id, (err, results1) => {
                    if(results1.length!= 1){
                        res.send({ // 返回前端信息
                            status: 500,
                            message: '添加失败,该菜地未存在产量信息，请先添加菜地产量信息',
                        });
                    }
                    else{
                        db.query(`select * from planting_cost where vegetableid=?`, results[0].id, (err, results2) => {
                            //
                            if(results2.length == 1){
                                res.send({ // 返回前端信息
                                    status: 500,
                                    message: '添加失败,该菜地已存在成本信息',
                                });
                            }else{
                                
                                req.body.vegetableid = results[0].id
                                const {id, name, ...rest} = req.body
                                db.query('INSERT INTO planting_cost SET ?', rest, (err, results3) => {
                                    if (err) {
                                      return res.cc('404', err.message)
                                    } else {
                                      res.send({
                                        status: 200,
                                        message: '添加成功',
                                      });
                                    }
                                  });
                            }
    
                        })
                    }
                })
            }
        })

    }
  }
  //更新
exports.up = (req, res)=>{
    const sql= 'update planting_cost  set seedcosts=?, fertilizercosts=?, pesticidecosts=?, laborcosts=?, othercosts=?, totalcosts=?, remarks=? WHERE id=?'
    db.query( sql, [req.body.seedcosts,req.body.fertilizercosts,req.body.pesticidecosts,req.body.laborcosts, req.body.othercosts, req.body.totalcosts, req.body.remarks, req.body.id], (err, results) =>{
        //
        if(err) return res.cc('404',err)
        if(results.affectedRows !== 1) return res.cc('500','修改失败')
        res.send({ // 返回前端信息
            status: 200,
            message: '修改成功',
        });
    })
}
//删除
exports.delete = (req, res)=>{
    const idToDelete = req.query.id;
    const sql = 'DELETE FROM planting_cost WHERE id = ?';
    db.query(sql, [idToDelete], (err, results) => {
        if(err) return res.cc('404', err);
        if(results.affectedRows !== 1) return res.cc('500', '删除失败');
        res.send({
            status: 200,
            message: '删除成功',
        });
    });
}